package ch.usi.inf.pf2.gui;

import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;

/**
 * JSpreadSheetCellEditor is the Cell editor of the JTable
 * 
 * @author Thomas Mantegazzi
 * 
 */

public class JSpreadSheetCellEditor extends AbstractCellEditor implements
		TableCellEditor {

	private JTextField textField;
	private JTable table;

	public JSpreadSheetCellEditor(JTextField text, JTable table) {
		this.textField = text;
		this.table = table;
	}

	/**
	 * tells the Table if a cell can be edited or not, and if it can be edited
	 * give the focus to the textField.
	 * 
	 * @return true if the cell can be edited and false if not.
	 */
	public boolean isCellEditable(EventObject evt) {
		if (evt instanceof MouseEvent) {
			int clickCount;

			// For double-click activation
			clickCount = 2;

			boolean b = ((MouseEvent) evt).getClickCount() >= clickCount;
			return b;
		}
		if (evt instanceof KeyEvent && !table.hasFocus()) {
			KeyEvent e = (KeyEvent) evt;
			if (e.getKeyCode() == KeyEvent.VK_RIGHT
					|| e.getKeyCode() == KeyEvent.VK_LEFT
					|| e.getKeyCode() == KeyEvent.VK_UP
					|| e.getKeyCode() == KeyEvent.VK_DOWN
					|| e.getKeyCode() == KeyEvent.VK_TAB
					|| e.getKeyCode() == KeyEvent.VK_TAB
					|| e.getKeyCode() == KeyEvent.VK_SPACE
					|| e.getKeyCode() == KeyEvent.VK_ESCAPE
					|| e.getKeyCode() == 157
					|| e.getModifiers() == KeyEvent.META_DOWN_MASK) {
				return false;
			} else {
				textField.grabFocus();
				textField.setEnabled(true);
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean stopCellEditing() {
		// TODO Auto-generated method stub
		return super.stopCellEditing();
	}

	@Override
	public Object getCellEditorValue() {
		// TODO Auto-generated method stub
		table.setRowHeight(((SpreadSheetTableModel) table.getModel())
				.getDefaultRowHight());
		return ((JTextField) textField).getText();
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value,
			boolean isSelected, int row, int column) {
		// TODO Auto-generated method stub
		textField.requestFocusInWindow();
		table.setRowHeight(row, 25);
		return textField;
	}

}
